﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Windows.Threading;

using System.Timers;

using SnakeGame.Data;
using SnakeGame.Logic;

namespace SnakeGame
{
    /// <summary>
    /// Логика взаимодействия для Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        //ПОМЕНЯТЬ НА ЭКЗ. КЛАССА LEVEL !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        private bool[,] _blObstacles = new bool[30, 30];

        //Значение скоростей змеек для таймера
        private int _iFirstrSnakeSpeed = 0;
        private int _iSecondSnakeSpeed = 0;

        //Координаты еды
        private int _iFoodCoordinateX, _iFoodCoordinateY;

        //Кнопки управления мейками
        private Key _keyFirstSnakeControls = new Key();
        private Key _keySecondSnakeControls = new Key();

        //координаты начало первой змейки
        private int[] _iCoordBeginFirstrSnakeXY = new int[2];

        //Массив змеек
        //j - строка, i - столбец
//        private bool[,] _blCoordinatesFirstSnake = new bool[30, 30];
//        private bool[,] _blCoordinatesSecondSnake = new bool[30, 30];

        //Таймеры змеек
        private Timer _timerFirstSnake = new Timer();
        private Timer _timerSecondSnake = new Timer();

        //Делегаты управления прорисовкой
        private delegate void SnakeHeadDelegate(int[] HeadCoordinates);
        private delegate void SnakeTailDelegate();
        private delegate void DrawFoodDelegate(int x, int y);
        private delegate void RemoveFoodDelegate();
        private delegate void DrawSnakeDelegate(List<int[]> _coordinates);
        
        //экземпляры класса логики
        private Log logicFirstSnake;
        
        //экземпляр класса уровня
        private Level level;

        //экземпляр класса змейки
        private Snake FirstSnake = new Snake();
        private Snake SecondSnake = new Snake();

        //экземпляр класса еды
        private Food food;

        //Обьявление экземпляра класса прорисовки
        private Sketching sketching;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            sketching = new Sketching(ImageLevel, ImageFood, ImageSnake1);
            level = new Level("1");

            FirstSnake._speed = 100;
            SecondSnake._speed = 30;

            FirstSnake._lives = 5;
            FirstSnake._score = 0;

            tbFirstSnakeLives.Text = FirstSnake._lives.ToString();
            tbFirstSnakeScore.Text = FirstSnake._score.ToString();

            //Задаем интервал движения первой змейки
            _timerFirstSnake.Interval = FirstSnake._speed;
            //Задаем интервал движения второй змейки
            _timerSecondSnake.Interval = SecondSnake._speed;

            CollisionManager collisionManager = new CollisionManager();

            int[] j = new int[] { 27, 10 };
            FirstSnake._coordinates.Add(j);
            int[] k = new int[] { 26, 10 };
            FirstSnake._coordinates.Add(k);
            int[] z = new int[] { 25, 10 };
            FirstSnake._coordinates.Add(z);

            level._coordinates.Add(j);
            level._coordinates.Add(k);
            level._coordinates.Add(z);

            _blObstacles[1, 1] = true;
            _blObstacles[1, 5] = true;
            _blObstacles[1, 2] = true;
            _blObstacles[15, 29] = true;
            _blObstacles[25, 14] = true;

            logicFirstSnake = new Log(_blObstacles, collisionManager);
            food = new Food(_blObstacles);
            

            collisionManager.NewCollision += newCollision;

            //Запускаем первую змейку
            _timerFirstSnake.Start();   
            _timerFirstSnake.Elapsed +=new ElapsedEventHandler(_timerFirstSnake_Elapsed);

            //Задаем начальное направление движение первой змейки влево 
            _keyFirstSnakeControls = Key.Left;

            //Генерируем новую еду
            food.GenerateCoordinates();
            _iFoodCoordinateX = food.GetX;
            _iFoodCoordinateY = food.GetY;

            //Прорисовываем данные
            sketching.DrawFood(_iFoodCoordinateX, _iFoodCoordinateY);
            sketching.DrawFirstSnake(FirstSnake._coordinates);
            sketching.SketchingLevel(_blObstacles);

            //Присваиваем координаты головы первой змейке
            _iCoordBeginFirstrSnakeXY[0] = 25;
            _iCoordBeginFirstrSnakeXY[1] = 10;


//!!!!!!!!!!!!!!!!!!!!!!!!!удалить !!!!!!!!!!!!!!!! 
//            List<int[]> _coor;
//            int[] c = new int[] { 27, 10 };            
//            _coor.Add(c);


        }

        /// <summary>
        /// Событие таймера первой змейки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _timerFirstSnake_Elapsed(object sender, EventArgs e)
        {
            int _iCheckEatenFood = 0;

            logicFirstSnake.AddSnakeHead(FirstSnake._coordinates, _iCoordBeginFirstrSnakeXY, _keyFirstSnakeControls);
            logicFirstSnake.CheckTheCollisionWithTheWall(_iCoordBeginFirstrSnakeXY, FirstSnake);
            _iCheckEatenFood = logicFirstSnake.CheckTheCollisionWithTheFood(_iFoodCoordinateX, 
                _iFoodCoordinateY, _iCoordBeginFirstrSnakeXY, FirstSnake);
            logicFirstSnake.CheckTheCollisionWithTheBody(FirstSnake._coordinates, _iCoordBeginFirstrSnakeXY, FirstSnake);

            Dispatcher.Invoke(new SnakeHeadDelegate(sketching.AddFirstSnakeHead), _iCoordBeginFirstrSnakeXY);
            if (_iCheckEatenFood == 0)
            {
                Dispatcher.Invoke(new SnakeTailDelegate(sketching.RemoveFirstSnakeTail), null);
                logicFirstSnake.RemoveTail(FirstSnake._coordinates);
            }
            else
            {
                Dispatcher.Invoke(new RemoveFoodDelegate(sketching.RemoveFood), null);
                food.GenerateCoordinates();
                _iFoodCoordinateX = food.GetX;
                _iFoodCoordinateY = food.GetY;
                Dispatcher.Invoke(new DrawFoodDelegate(sketching.DrawFood), _iFoodCoordinateX, _iFoodCoordinateY);
            }
        }

        /// <summary>
        /// Событие остановки таймера при каких либо проишествиях со змейкой
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newCollision(object sender, NewCollisionEventArgs e)
        {
            _timerFirstSnake.Stop();

            if (e.GameStatus == "Process")
            {
                Dispatcher.Invoke(new SnakeTailDelegate(sketching.RemoveFirstSnake), null);
                Dispatcher.Invoke(new DrawSnakeDelegate(sketching.DrawFirstSnake), level._coordinates);
                _iCoordBeginFirstrSnakeXY[0] = 25;
                _iCoordBeginFirstrSnakeXY[1] = 10;
                FirstSnake._coordinates = level._coordinates;
                _keyFirstSnakeControls = Key.Left;
//                FirstSnake._coordinates.Clear();
                _timerFirstSnake.Start();
            }
            else
            {
                MessageBox.Show("Игра окончена");
            }
        }

        /// <summary>
        /// События нажатия кнопок управления змеек
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Window_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Up:
                    //if (_keyFirstSnakeControls != Key.Down)  
                        _keyFirstSnakeControls = e.Key;
                    break;
                case Key.Down:
                   // if (_keyFirstSnakeControls != Key.Up)
                        _keyFirstSnakeControls = e.Key;
                    break;
                case Key.Left:
                   // if (_keyFirstSnakeControls != Key.Right)
                        _keyFirstSnakeControls = e.Key;
                    break;
                case Key.Right:
                   // if (_keyFirstSnakeControls != Key.Left) 
                        _keyFirstSnakeControls = e.Key;
                    break;
            };

 /*           //Проверочные данные (мусор)
            textBox1.Clear();

            for (int j = 0; j < 30; j++)
            {
                for (int i = 0; i < 30; i++ )
                {
                    if (_blCoordinatesFirstSnake[i, j] == true)
                        textBox1.Text += 1 + "   ";
                    else
                        textBox1.Text += 0 + "   ";
                }
                textBox1.Text += "\n";
            }
            //end
*/
            e.Handled = true;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            sketching.RemoveFood();
        }
    }
}
